package com.seckill.service.impl;

import com.seckill.dao.SeckillDao;
import com.seckill.dao.SuccessKilledDao;
import com.seckill.dao.cache.RedisDao;
import com.seckill.dto.Exposer;
import com.seckill.dto.SeckillExecution;
import com.seckill.entity.Seckill;
import com.seckill.entity.SuccessKilled;
import com.seckill.enums.SeckillStateEnum;
import com.seckill.exception.RepeatSecKillException;
import com.seckill.exception.SeckillCloseException;
import com.seckill.exception.SeckillException;
import com.seckill.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by chengweixin on 2017/4/25.
 */
// 注解
// @Component
// @Service
// @Dao
// @Controller
@Service
public class SeckillServiceImpl implements SeckillService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    // 注入Service依赖
    @Autowired // @Resource , @Inject (j2ee规范注解)
    private SeckillDao seckillDao;
    @Autowired
    private SuccessKilledDao successKilledDao;

    @Autowired
    private RedisDao redisDao;

    private final String mix = "*#!(N7sdf1%FE*&T*";

    public List<Seckill> getSeckillList() {
        return seckillDao.getAll(0, 40);
    }

    public Seckill getSeckill(long seckillId) {
        return seckillDao.getSeckill(seckillId);
    }

    // 秒杀开启时:秒杀接口地址,否则输出系统时间和秒杀时间
    public Exposer exportSeckillUrl(long seckillId) {
        // 缓存优化
        // redis缓存接口地址
        // get from cache
        // if null
        //  get db
        // else
        //  put cache
        // 逻辑应该写在dao层


        // 1. 访问redis
        Seckill seckill = redisDao.getSeckill(seckillId);
        if (seckill == null) {
            // 2.访问数据库
            seckill = seckillDao.getSeckill(seckillId);
            if (seckill == null) {
                return new Exposer(false, seckillId);
            } else {
                // 3.放入redis缓存
                redisDao.putSeckill(seckill);
            }
        }

        Date startTime = seckill.getStartTime();
        Date endTime = seckill.getEndTime();
        Date nowTime = new Date();
        if (nowTime.getTime() < startTime.getTime()
                || nowTime.getTime() > endTime.getTime()) {
            return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());
        }

        String md5 = getMD5(seckillId);
        return new Exposer(true, md5, seckillId);
    }

    private String getMD5(long seckillId) {
        String base = seckillId + "/" + mix;
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
        return md5;
    }

    @Transactional
    /**
     * 使用注解控制事物方法的有点:
     * 1. 开发人员达成一致的约定,明确标注事物方法的编程风格.
     * 2. 保证事物方法的执行时间尽可能短,不要穿插其他的网络操作.(RPC/HTTP请求),或者剥离到事物方法外.
     * 3. 不是所有的方法都需要事物,如只有一条修改操作,只读操作,不需要事物控制.
     */
    public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5) throws SeckillException, SeckillCloseException, RepeatSecKillException {

        if (md5 == null || !md5.equals(getMD5(seckillId))) {
            throw new SeckillException("seckill data rewrite");
        }

        // 执行秒杀逻辑:减库存 + 生成秒杀订单
        Date nowTime = new Date();
        int updateCount = seckillDao.reduceNumber(seckillId, nowTime);
        try {
            if (updateCount <= 0) {
                // 没有秒杀成功,没有生成记录,秒杀结束
                throw new SeckillCloseException("seckill is closed");
            } else {
                // 记录购买行为
                int insertCount = successKilledDao.insertSuccessKilled(seckillId, userPhone);
                // 唯一: seckillId + userPhone
                if (insertCount <= 0) {
                    throw new RepeatSecKillException("seckill repeated");
                } else {
                    SuccessKilled successKilled = successKilledDao.getSuccessKilledWithSeckill(seckillId, userPhone);

                    return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successKilled);
                }
            }
        } catch (SeckillCloseException e1) {
            throw e1;
        } catch (RepeatSecKillException e2) {
            throw e2;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            // 所有编译期异常,转化为运行期异常
            throw new SeckillException("seckill inner error:" + e.getMessage());
            // Spring --> 回滚
            // 保证业务正确!
        }
    }
}
